package org.kinglone.back.article.action;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.kinglone.back.article.model.Article;
import org.kinglone.back.article.service.ArticleService;
import org.kinglone.back.classify.model.Classify;
import org.kinglone.back.classify.service.ClassifyService;
import org.kinglone.common.util.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/article")
public class ArticleAction {

	@Resource(name="articleService")
	private ArticleService articleService;

	@Resource(name="classifyService")
	private ClassifyService classifyService;

	/**
	 * 跳转到后台文章管理页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/selectArticle.jspx")
	public ModelAndView selectArticle(HttpServletRequest request){
		ModelAndView modelAndView = new ModelAndView("/WEB-INF/jsp/back/article/articleList.jsp");
		return modelAndView;
	}
	/**
	 * 分页查询文章列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/seltArticleList.jspx")
	public JSONMessageView seltArticleList(HttpServletRequest request){
		JSONMessageView json = new JSONMessageView(-1,"查询失败!",null);
		try {
			String title = request.getParameter("title");
			String pageNo = request.getParameter("pageNo");
			String pageSize = request.getParameter("pageSize");
			PageQuery pageQuery = new PageQuery();
			pageQuery.setStart((Integer.parseInt(pageNo)-1)*Integer.parseInt(pageSize));
			pageQuery.setLength(Integer.parseInt(pageSize));
			PageResults<Article> list =articleService.findArticleByPage(pageQuery,title);
			JSONArray totalJsonArray = new JSONArray();
			JSONObject totalJsonObject = new JSONObject();
			JSONArray jsonArray=new JSONArray();
			for(Article a : list.getResults()) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("sysid", a.getSysid());
				jsonObject.put("title",a.getTitle());
				jsonObject.put("content",a.getContent());
				jsonObject.put("author",a.getAuthor());
				jsonObject.put("briefing",a.getBriefing());
				jsonObject.put("publishDatetime",a.getPublishDatetime());
				if(a.getClassifyId() != null){
					Classify classify = classifyService.get(a.getClassifyId());
					if(classify != null){
						jsonObject.put("classifyName",classify.getClassifyName());	
					}else{
						jsonObject.put("classifyName","");
					}
				}else{
					jsonObject.put("classifyName","");
				}												
				jsonObject.put("label",a.getLabel());
				jsonObject.put("isDisplay",a.getIsDisplay());
				jsonObject.put("isComment",a.getIsComment());
				jsonArray.add(jsonObject);
			}
			totalJsonObject.put("pagetotal", list.getPageCount());//总页数
			totalJsonObject.put("info", jsonArray);
			totalJsonArray.add(totalJsonObject);
			json.setCode(0);
			json.setMessage("查询成功!");
			json.setContent(totalJsonArray);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			json.setCode(-1);
			json.setMessage("服务器异常,请稍后再试!");
			return json;
		}
	}

	/**
	 * 跳转到后台添加文章页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/showAddArticle.jspx")
	public ModelAndView showAddArticle(HttpServletRequest request){
		ModelAndView modelAndView = new ModelAndView("/WEB-INF/jsp/back/article/addArticle.jsp");
		List<Classify> classifies = classifyService.getAll();
		modelAndView.addObject("classifies", classifies);
		return modelAndView;
	}

	/**
	 * 跳转到后台修改文章页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateArticle.jspx")
	public ModelAndView updateArticle(HttpServletRequest request){
		ModelAndView modelAndView = new ModelAndView("/WEB-INF/jsp/back/article/updateArticle.jsp");
		String articleId=request.getParameter("articleId");
		if(articleId != null){
			Article article = articleService.get(articleId);
			request.setAttribute("article",article);
		}
		List<Classify> classifies = classifyService.getAll();
		modelAndView.addObject("classifies", classifies);
		return modelAndView;
	}

	/**
	 * 富文本上传图片
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/image/fileUpload.jspx")
	public JSONMessageView fileUpload(HttpServletRequest request, Model model) {
		JSONMessageView json = new JSONMessageView(-1, "上传失败!", null);
		try {
			Map<String, String> map = FileUtils.saveByRequest(request, "blog", 1024 * 1024, null, null);
			for (String key : map.keySet()) {
				if (map.get(key).equals("error")) {
					json.setCode(-1);
					json.setMessage("上传图片太大");
				} else {
					json.setCode(0);
					json.setMessage("上传成功!");
					json.setContent(map.get(key));
					System.out.println(json);
				}
				break;
			}
			return json;
		} catch (Exception e) {
			e.printStackTrace();
			json.setCode(-1);
			json.setMessage("服务器异常,请稍候再试!");
			return json;
		}

	}

	/**
	 * 添加或修改文章
	 * @param request
	 * @return
	 */
	@RequestMapping("/saveOrUpdateArticle.jspx")
	public JSONMessageView saveOrUpdateArticle(HttpServletRequest request){
		JSONMessageView json = new JSONMessageView(-1, "保存失败!", null);
		try {
			String sysid = request.getParameter("id");
			String title = request.getParameter("title");
			String label =request.getParameter("label");
			String regContext = request.getParameter("content");
			String briefing = request.getParameter("briefing");
			String isDisplay = request.getParameter("isDisplay");
			String isComment = request.getParameter("isComment");
			String classifyId = request.getParameter("classifyId");
			if(StringUtil.isNullOrEmpty(regContext)){
				json.setCode(-1);
				json.setMessage("请输入标题!");
				return json;
			}
			if(StringUtil.isNullOrEmpty(regContext)){
				json.setCode(-1);
				json.setMessage("请输入内容!");
				return json;
			}
			if(StringUtil.isNullOrEmpty(regContext)){
				json.setCode(-1);
				json.setMessage("请输入简介!");
				return json;
			}
			if(StringUtil.isNullOrEmpty(sysid)){
				Article article = new Article();
				article.setAuthor("kinglone");
				article.setTitle(title);
				article.setContent(regContext);
				article.setBriefing(briefing);
				if(StringUtil.isNullOrEmpty(classifyId)){
					article.setClassifyId("");
				}
				article.setClassifyId(classifyId);
				article.setIsComment(isComment);
				article.setIsDisplay(isDisplay);
				article.setLabel(label);
				article.setCreateTime(new Date());
				article.setPublishDatetime(DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
				article.setModifyTime(DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
				articleService.save(article);
				json.setCode(0);
				json.setMessage("保存成功!");
				return json;
			}else{
				Article article = articleService.get(sysid);
				article.setContent(regContext);
				article.setTitle(title);
				article.setClassifyId(classifyId);
				article.setIsComment(isComment);
				article.setIsDisplay(isDisplay);
				article.setBriefing(briefing);
				article.setLabel(label);
				article.setModifyTime(DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
				article.setPublishDatetime(DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
				articleService.update(article);
				json.setCode(0);
				json.setMessage("修改成功!");
				return json;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			json.setCode(-1);
			json.setMessage("服务器异常，请稍候再试!");
			return json;
		}
	}
	

	/**
	 * 是否显示
	 * @param request
	 * @return
	 */
	@RequestMapping("/isShow.jspx")
	public JSONMessageView isShow(HttpServletRequest request){
		JSONMessageView json = new JSONMessageView(-1,"设置失败!",null);
		try {
			String articleId = request.getParameter("articleId");
			Article article = articleService.get(articleId);
			if(article.getIsDisplay().equals("Y")){
				article.setIsDisplay("N");
			}else{
				article.setIsDisplay("Y");
			}
			articleService.update(article);
			json.setCode(0);
			json.setMessage("设置成功!");
			return json;
		}catch (Exception e){
			e.printStackTrace();
			json.setCode(-1);
			json.setMessage("服务器异常,请稍候再试!");
			return json;
		}
	}

	/**
	 * 是否允许评论
	 * @param request
	 * @return
	 */
	@RequestMapping("/isComment.jspx")
	public JSONMessageView isComment(HttpServletRequest request){
		JSONMessageView json = new JSONMessageView(-1,"设置失败!",null);
		try {
			String articleId = request.getParameter("articleId");
			Article article = articleService.get(articleId);
			if(article.getIsComment().equals("Y")){
				article.setIsComment("N");
			}else{
				article.setIsComment("Y");
			}
			articleService.update(article);
			json.setCode(0);
			json.setMessage("设置成功!");
			return json;
		}catch (Exception e){
			e.printStackTrace();
			json.setCode(-1);
			json.setMessage("服务器异常,请稍候再试!");
			return json;
		}
	}

	/**
	 * 根据id删除文章
	 * @param request
	 * @return
	 */
	@RequestMapping("/delArticle.jspx")
	public JSONMessageView delArticle(HttpServletRequest request){
		JSONMessageView json = new JSONMessageView(-1,"删除失败!",null);
		try{
			String articleId = request.getParameter("articleId");
			articleService.deleteById(articleId);
			json.setCode(0);
			json.setMessage("删除成功!");
			return json;
		}catch (Exception e){
			e.printStackTrace();
			json.setCode(-1);
			json.setMessage("服务器异常,请稍后再试!");
			return json;
		}
	}

	/**
	 * 批量删除文章
	 * @param request
	 * @return
	 */
	@RequestMapping("/delMoreArticle.jspx")
	public JSONMessageView delMoreArticle(HttpServletRequest request){
		JSONMessageView json = new JSONMessageView(-1,"删除失败!",null);
		try{
			String ids = request.getParameter("ids");
			String[] idArr = ids.split(",");
			for(int i=0;i < idArr.length;i++ ){
				articleService.deleteById(idArr[i]);
			}
			json.setCode(0);
			json.setMessage("删除成功!");
			return json;
		}catch (Exception e){
			e.printStackTrace();
			json.setCode(-1);
			json.setMessage("服务器异常,请稍后再试!");
			return json;
		}
	}



}
